package com.ijpay.interceptor;

import com.ijpay.controller.IJPayConsts;
import com.ijpay.model.Alipay;
import com.ijpay.model.App;
import com.ijpay.service.AlipayService;
import com.ijpay.service.AppService;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.LogKit;
import com.jpay.alipay.AliPayApiConfig;
import com.jpay.alipay.AliPayApiConfigKit;
import com.jpay.ext.kit.StrKit;
import com.jpay.vo.AjaxResult;

/**
 * @Email javen205@126.com
 * @author Javen
 */
public class AliPayApiInterceptor implements Interceptor {
	AlipayService alipayService = new AlipayService();
	AppService appService = new AppService();
	AjaxResult ajax = new AjaxResult();
	
	@Override
	public void intercept(Invocation inv) {
		Controller controller = inv.getController();
		String appId = controller.getPara("appId");
		if (StrKit.isBlank(appId)) {
			controller.renderJson(ajax.addError("应用的编号不能为空"));
			return;
		}
		//判断应用是否存在
		App app = appService.getAppByAppId(appId, 1);
		AliPayApiConfig aliPayApiConfig = null;
		if (app !=null) {
			// 通过应用的appId查询支付宝的配置
			Alipay alipay = alipayService.getAlipayByAppId(appId);
			if (alipay != null) {
				try {
					aliPayApiConfig = AliPayApiConfigKit.getApiConfig(alipay.getAppId());
				} catch (Exception e) {
					LogKit.error("实例化AliPayApiConfig...");
					// 如果Map中没有当前支付宝的实例就初始化并添加到Map中
					aliPayApiConfig = AliPayApiConfig.New()
							.setAppId(alipay.getAppId())
							.setAlipayPublicKey(alipay.getPublicKey())
							.setCharset(IJPayConsts.CHARSET)
							.setPrivateKey(alipay.getPrivateKey())
							.setServiceUrl(alipay.getServerUrl())
							.setSignType(IJPayConsts.SIGN_TYPE)
							.build();
				}
			}
		}
		if (aliPayApiConfig != null) {
			AliPayApiConfigKit.setThreadLocalAliPayApiConfig(aliPayApiConfig);
			controller.setAttr("app", app);
			inv.invoke();
		} else {
			LogKit.error("aliPayApiConfig is null");
			controller.renderJson(ajax.addError("此应用暂未配置支付宝支付的参数"));
		}
	}
}